import Vue from 'vue'
import Router from 'vue-router'
import store from '@/store'
import { businessRouter } from './businessRouter' // 业务模块
import { approveRouter } from './approveRouter' // 审批中心
// 公用组件
import Layout from 'views/layout'
import TopNav from 'common/components/nav/topNav.vue'
import LeftNav from 'common/components/nav/leftNav.vue'
import ChildView from 'common/components/ChildView' // 三级路由视图层
// 我的
import ChangeAutor from 'views/changeUserInfo/components/changeAutor'
import ChangePwd from 'views/changeUserInfo/components/changePwd'

Vue.use(Router)

/**
 * @param {defaultRouter}
 * 默认路由
 */

export const defaultRouter = [
  // 通用模块
  {
    path: '/login',
    type: 'login',
    component: () => import('views/login')
  },
  {
    path: '/erro',
    component: () => import('views/error')
  },
  {
    path: '/preview',
    component: () => import('views/previewPage')
  },
  { path: '*', redirect: '/erro', hidden: true },
  // 首页
  {
    path: '/',
    component: () => import('views/dashboard')
  },
  // 帮助中心
  {
    path: '/helpcenter',
    component: () => import('views/helpcenter')
  },
  // 意见建议
  {
    path: '/suggest',
    component: () => import('views/suggest')
  },
  // 我的
  {
    path: '/my',
    type: 'my',
    name: 'my',
    title: '我的',
    component: Layout,
    redirect: '/my',
    menuShow: false,
    iconCls: 'icon-caidan',
    children: [
      {
        path: '/my',
        name: '我的',
        components: {
          content: ChildView,
          top: TopNav,
          aside: LeftNav
        },
        menuShow: true,
        iconCls: 'icon-caidan',
        meta: { title: '我的' },
        redirect: '/my/changeAutor',
        children: [
          {
            path: '/my/changeAutor',
            name: '修改头像',
            components: {
              content: ChangeAutor,
              top: TopNav,
              aside: LeftNav
            },
            // leaf: true,
            menuShow: true,
            meta: { title: '修改头像' }
          },
          {
            path: '/my/changePwd',
            name: '修改密码',
            components: {
              content: ChangePwd,
              top: TopNav,
              aside: LeftNav
            },
            leaf: true,
            menuShow: true,
            iconCls: 'icon-zhediexiaoguo',
            meta: { title: '修改密码' }
          }]
      }
    ]
  }
]

// 合并模块路由
const allRouters = [...defaultRouter, ...businessRouter, ...approveRouter]
const createRouter = function () {
  let router = new Router({
    // mode: 'history', // require service support
    scrollBehavior: () => ({ y: 0 }),
    routes: allRouters
  })

  // 业务逻辑处理
  if (!router.routeByListCache) {
    let result = []
    routeTreeToList(router.options.routes, result)
    router.routeByListCache = result
  }
  if (!router.operationsByUnAuthPathCache) {
    router.operationsByUnAuthPathCache = {}
  }
  if (!router.activeOperationsCache) {
    router.activeOperationsCache = {}
  }
  if (!router.operationsAllCache) {
    router.operationsAllCache = []
  }
  if (!router.unAuthRouteMap) {
    router.unAuthRouteMap = {}
  }
  return router
}

const router = createRouter()

// 全局之前
// 获取非配置页面的所有操作权限
router.beforeResolve((to, form, next) => {
  let toPath = to.path
  console.log('即将进入【' + toPath + '】页面')
  // 需要提前初始化
  if ((!router.routeByListCache) || router.routeByListCache.length <= 0) {
    let result = []
    routeTreeToList(router.options.routes, result)
    router.routeByListCache = result
  }
  if (!router.unAuthRouteMap) {
    router.unAuthRouteMap = {}
  }

  // 当前穿透路由地址不存在权限路由中
  let unRoute = null
  if (router.unAuthRouteMap[toPath]) {
    unRoute = router.unAuthRouteMap[toPath]
  } else {
    for (let i = 0; i < router.routeByListCache.length; i++) {
      let p = router.routeByListCache[i]
      if (p.path === toPath && p.route && p.route.unAuthPage && p.route.unAuthPage.checkAllOperation) {
        unRoute = p
        router.unAuthRouteMap[toPath] = p
        break
      }
    }
  }
  if (unRoute) {
    let parentPath = unRoute.route.unAuthPage.parentPath
    let currentPath = unRoute.route.path
    if (!router.operationsByUnAuthPathCache) {
      console.log('第一次初始化----------------> operationsByUnAuthPathCache')
      router.operationsByUnAuthPathCache = {}
    }
    let unOperatios = router.operationsByUnAuthPathCache[currentPath]
    if (!unOperatios || unOperatios.length <= 0) {
      Vue.prototype.$$get(Vue.prototype.$$api.operation.findByPath(parentPath)).then(resp => {
        if (resp.success) {
          router.operationsByUnAuthPathCache[currentPath] = resp.content
          console.log('第一次获取非授权的地址【' + currentPath + '】', resp.content)
          next()
        } else {
          next('/error')
        }
      }, () => {
        next('/error')
      })
    } else {
      next()
    }
  } else {
    next()
  }
})

// 处理组件权限操作
router.handelAuthOperations = function (this_) {
  let unOperatios = this.operationsByUnAuthPathCache[this_.$route.path]
  if (unOperatios && unOperatios.length > 0) {
    // // 处理未授权的穿透页面
    this.handelActiveOperations(this_, unOperatios)
  } else {
    // 处理当前页操作权限
    let activeOperations = this.getActiveOperations(this_.$store.getters.authRouters, this_.$route.path)
    // console.log('activeOperations:', activeOperations)
    this.handelActiveOperations(this_, activeOperations)
  }
}

/**
 * 处理当前组件 操作权限 是否去掉EL
 * @param this_ >>>>>>>>>>>> 组件内的 vue 实例
 * @param activeOperations 操作权限集合
 */
router.handelActiveOperations = function (this_, activeOperations) {
  if (activeOperations && activeOperations.length > 0) {
    activeOperations.forEach(o => {
      if (o.type === 'ID' && o.auth === 0) {
        let el = document.querySelector('#' + o.code)
        if (el) {
          el.remove()
        }
      } else {
        let els = document.querySelectorAll('.' + o.code)
        if (els && els.length > 0 && o.auth === 0) {
          els.forEach(e => e.remove())
        }
      }
    })
  }
}

// 获取routeByList
router.getRouteByListCache = function () {
  if (!this.routeByListCache || this.routeByListCache.length <= 0) {
    let result = []
    routeTreeToList(router.options.routes, result)
    this.routeByListCache = result
  }
  return this.routeByListCache
}

/**
 * 获取当前角色所有操作权限集合
 * @param authRouters 》》》》 this.$store.getters.authRouters
 * @returns {Array}
 */
router.getOperationsAll = function (authRouters) {
  if (this.operationsAllCache.length > 0) {
    return this.operationsAllCache
  } else {
    let result = []
    routeTreeToList(Object.assign(authRouters), result)
    let rs = []
    for (let i = 0; i < result.length; i++) {
      rs.push(...result[i].operations)
    }
    this.operationsAllCache = rs
    return rs
  }
}

/**
 * 获取当前路由地址的操作权限集合
 * @param authRouters 》》》》 this.$store.getters.authRouters
 * @param path 》》》》this.$route.path
 * @returns {*}
 */
router.getActiveOperations = function (authRouters, path) {
  let cache = router.activeOperationsCache[path]
  if (cache) {
    return cache
  } else {
    let ar = Object.assign({}, authRouters)
    let list = []
    routeTreeToList(ar, list)
    let rs = []
    const ls2 = list.filter((a) => {
      return path.indexOf(a.path) > -1
    })
    if (ls2) {
      ls2.forEach(a => {
        rs.push(...a.operations)
      })
    }
    router.activeOperationsCache[path] = rs
    return rs
  }
}

/**
 * 获取当前路由对象
 * @param routerPath 》》》》 this.$route.path
 * @returns {*}
 */
router.getRouteByPath = function (routerPath) {
  for (let i = 0; i < this.routeByListCache.length; i++) {
    if (this.routeByListCache[i].path === routerPath) {
      return this.routeByListCache[i]
    }
  }
  return null
}

/**
 * 获取未授权页面对象
 * @param routerPath 》》》》 this.$route.path
 * @returns {unAuthPage|{checkAllOperation, parentPath}}
 */
router.getUnAuthPage = function (routerPath) {
  let ls = this.getRouteByPath(routerPath)
  if (ls) {
    return ls.route.unAuthPage
  }
}

// 重新配置数据时需清理数据
router.clearData = function () {
  router.activeOperationsCache = {}
  this.getActiveOperations(store.getters.authRouters, router.currentRoute.path)
}

/**
 * tree to list
 * @param routes
 * @returns {Array}
 */
export function routeTreeToList (routes, result) {
  const rus = Object.assign(routes)
  let array = []
  if (!(rus instanceof Array)) {
    for (let k in rus) {
      array.push(rus[k])
    }
  } else {
    array = rus
  }
  if (array && array.length > 0) {
    for (let i = 0; i < array.length; i++) {
      let arr = array[i]
      result.push({ path: arr.path, operations: arr.operations })
      if (arr.children && arr.children.length > 0) {
        routeTreeToList(arr.children, result)
      }
    }
  }
}

export function resetRouter () {
  const newRouter = createRouter()
  router.matcher = newRouter.matcher // reset router
}

export default router
